package wnhz.com.business.shareshop.ui;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.lzy.imagepicker.ImagePicker;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import wnhz.com.business.MyApplication;
import wnhz.com.business.R;
import wnhz.com.business.base.BaseActivity;
import wnhz.com.business.changepwd.ChangePwd1Activity;
import wnhz.com.business.groupshop.ui.AllOrderActivity;
import wnhz.com.business.impl.ActionBarClickListener;
import wnhz.com.business.shareshop.bean.BankListBean;
import wnhz.com.business.uitls.Base64Util;
import wnhz.com.business.uitls.LogUtils;
import wnhz.com.business.uitls.MyCallBack;
import wnhz.com.business.uitls.ToastUtils;
import wnhz.com.business.uitls.Url;
import wnhz.com.business.uitls.XUtil;
import wnhz.com.business.uitls.dialog.EnterCodeDialog;
import wnhz.com.business.uitls.dialog.SimpleDialog;
import wnhz.com.business.view.TranslucentActionBar;

public class PayChongzhiActivity extends BaseActivity implements ActionBarClickListener {

    @BindView(R.id.tv_allprice)
    TextView tv_allprice;
    @BindView(R.id.tv_can_money)
    TextView tv_can_money;
    @BindView(R.id.ll_yue)
    LinearLayout ll_yue;
    @BindView(R.id.ll_wx)
    LinearLayout ll_wx;
    @BindView(R.id.ll_zhifubao)
    LinearLayout ll_zhifubao;
    @BindView(R.id.ll_yinlian)
    LinearLayout ll_yinlian;
    @BindView(R.id.card)
    TextView card;
    @BindView(R.id.actionbar)
    TranslucentActionBar actionbar;

    @BindView(R.id.lay_submit)
    TextView lay_submit;
    @BindView(R.id.btn_yue)
    ImageView btn_yue;
    @BindView(R.id.btn_wx)
    ImageView btn_wx;
    @BindView(R.id.textView)
    TextView textView;
    @BindView(R.id.btn_zhifubao)
    ImageView btn_zhifubao;
    @BindView(R.id.textView2)
    TextView textView2;
    @BindView(R.id.btn_yinlian)
    ImageView btn_yinlian;
    @BindView(R.id.ll_moreWay)
    LinearLayout llMoreWay;
    @BindView(R.id.lay)
    LinearLayout lay;

    private EnterCodeDialog dialog;
    private SimpleDialog simpleDialog;
    private Context context;
    private String price;
    private String order_no;
    private String order_id;
    private String yue,id;//银行卡id
    private String from,way="1",amount;
    private String pay_class="1";// pay_class  支付类型  1：立即购买下单支付  2：购物车下单支付  0119  zhangjie

    public static Intent createIntent(Context context, String order_no, String price, String from) {
        Intent intent = new Intent(context, PayChongzhiActivity.class);
        intent.putExtra("order_no", order_no);
        intent.putExtra("price", price);
        intent.putExtra("from", from);
        intent.putExtra("pay_class", "1");
        return intent;
    }
    public static Intent createIntent(Context context, String order_id,String order_no, String price, String from, String pay_class) {
        Intent intent = new Intent(context, PayChongzhiActivity.class);
        intent.putExtra("order_id", order_id);
        intent.putExtra("order_no", order_no);
        intent.putExtra("price", price);
        intent.putExtra("from", from);
        intent.putExtra("pay_class", pay_class);
        return intent;
    }

    public void parseIntent() {
        Intent intent = getIntent();
        price = intent.getStringExtra("price");
        order_no = intent.getStringExtra("order_no");
        order_id = intent.getStringExtra("order_id");
        from = intent.getStringExtra("from");
        pay_class = intent.getStringExtra("pay_class");
        way = intent.getStringExtra("way");
        amount = intent.getStringExtra("amount");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pay_chongzhi);
        ButterKnife.bind(this);
        parseIntent();
        actionbar.setData("选择支付方式", R.drawable.ic_lefft_white, null, 0, null, 0, this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            actionbar.setStatusBarHeight(getStatusBarHeight());
        }

        initData();
    }

    private void initData() {
        Map<String, Object> map = new HashMap<>();
        map.put("token", MyApplication.getToken());
        XUtil.Post(Url.UCENTER_WITHDRAWALSDATA, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                LogUtils.e("== 支付界面  余额 ==", result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if ("1".equals(jsonObject.optString("re"))) {
                        tv_can_money.setText("余额："+Base64Util.decodedString2(jsonObject.optString("balance")+"元"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
            }
        });
    }


   // 返回键
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (from.equals("1")) {
                startActivity(AllOrderActivity.createIntent(PayChongzhiActivity.this, "2"));
            }else  if (from.equals("41")) {//共享商城直接购买
                startActivity(wnhz.com.business.shareshop.activity.mine.AllOrderActivity.createIntent(PayChongzhiActivity.this, "2"));
            }
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onLeftClick() {
        finish();
    }

    @Override
    public void onRightClick() {

    }

    @Override
    public void onEditTextClick() {

    }

    private int payType=4; //type       支付方式  1微信支付，2支付宝，3银联，4余额
    @OnClick({R.id.ll_yue, R.id.ll_wx, R.id.ll_zhifubao, R.id.ll_yinlian,R.id.lay_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_yue:
                btn_yue.setImageDrawable(getResources().getDrawable(R.drawable.ic_home_selected));
                btn_wx.setImageDrawable(getResources().getDrawable(R.drawable.ic_home_unselected));
                btn_zhifubao.setImageDrawable(getResources().getDrawable(R.drawable.ic_home_unselected));
                btn_yinlian.setImageDrawable(getResources().getDrawable(R.drawable.ic_home_unselected));
                payType=4;
                break;
            case R.id.ll_wx:
                btn_yue.setImageDrawable(getResources().getDrawable(R.drawable.ic_home_unselected));
                btn_wx.setImageDrawable(getResources().getDrawable(R.drawable.ic_home_selected));
                btn_zhifubao.setImageDrawable(getResources().getDrawable(R.drawable.ic_home_unselected));
                btn_yinlian.setImageDrawable(getResources().getDrawable(R.drawable.ic_home_unselected));
                payType=1;
                break;
            case R.id.ll_zhifubao:
                btn_yue.setImageDrawable(getResources().getDrawable(R.drawable.ic_home_unselected));
                btn_wx.setImageDrawable(getResources().getDrawable(R.drawable.ic_home_unselected));
                btn_zhifubao.setImageDrawable(getResources().getDrawable(R.drawable.ic_home_selected));
                btn_yinlian.setImageDrawable(getResources().getDrawable(R.drawable.ic_home_unselected));
                payType=2;
                break;
            case R.id.ll_yinlian:
                btn_yue.setImageDrawable(getResources().getDrawable(R.drawable.ic_home_unselected));
                btn_wx.setImageDrawable(getResources().getDrawable(R.drawable.ic_home_unselected));
                btn_zhifubao.setImageDrawable(getResources().getDrawable(R.drawable.ic_home_unselected));
                btn_yinlian.setImageDrawable(getResources().getDrawable(R.drawable.ic_home_selected));
                Intent intents = new Intent(PayChongzhiActivity.this, CardChooseActivity.class);
                startActivityForResult(intents, 1);
                payType=3;
                break;


        case R.id.lay_submit:
                if (payType==4){
                    postData();
//                    yuePay();
                }else if (payType==1){
                    MyToast("微信支付暂未开通");
                }else if (payType==2){
                    MyToast("支付宝支付暂未开通");
                }else if (payType==3){
                    postData();
//                    MyToast("银联支付暂未开通");
                }
                break;

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {

            if (data != null) {
                switch (requestCode) {
                    case 1:
                        BankListBean.InfoBean item = (BankListBean.InfoBean) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                        card.setText(item.getBank_name()+"尾号"+item.getBank_num());
                        id = item.getBank_id();
                        break;
                }
            }
        }
    }

    private void yuePay() {
        dialog = new EnterCodeDialog(PayChongzhiActivity.this, "请输入交易密码", price, new EnterCodeDialog.OnEnterCompleted() {
            @Override
            public void OnEnterCompleted(String content) {
                Map<String, Object> map = new HashMap<>();
                /**
                 * 未支付订单去支付
                 @param	Str     order_no   订单编号
                 @param	Int     password   交易密码  type为4时必传
                 @param	Int     type       支付方式  1微信支付，2支付宝，3银联，4余额
                 @param	Str     token
                 @param    Str     pay_class  支付类型  1：立即购买下单支付  2：购物车下单支付  0119  zhangjie
                 */
                map.put("token", MyApplication.getToken());
                map.put("order_no", order_no);
                map.put("type", 4);
                map.put("password", Base64Util.encodedString2(content));
                map.put("pay_class", pay_class);

                XUtil.Post(Url.PAY_TOPAY, map, new MyCallBack<String>() {
                    @Override
                    public void onSuccess(String result) {
                        super.onSuccess(result);
                        try {
                            JSONObject jsonObject = new JSONObject(result);
                            LogUtils.e("=======余额支付结果========", result);
                            if ("1".equals(jsonObject.optString("re"))) {
                                if (from.equals("1")) {
                                    startActivity(AllOrderActivity.createIntent(PayChongzhiActivity.this, "2"));
                                }else  if (from.equals("41")) {//共享商城直接购买
                                    startActivity(wnhz.com.business.shareshop.activity.mine.AllOrderActivity.createIntent(PayChongzhiActivity.this, "2"));
                                    finish();
                                }
                                ToastUtils.showToast(context, "支付成功");
                            }else if ("2".equals(jsonObject.optString("re"))){
                                ToastUtils.showToast(context, "请先设置交易密码");
                                Intent intent = new Intent(PayChongzhiActivity.this, ChangePwd1Activity.class);
                                intent.putExtra("type","5");
                                startActivity(intent);
                            }else{
                                ToastUtils.showToast(context, jsonObject.optString("info"));
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFinished() {
                        super.onFinished();
                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {
                        super.onError(ex, isOnCallback);

                    }
                });
            }
        }, new EnterCodeDialog.OnButtonClick() {
            @Override
            public void onCancleBtnClick() {
                dialog.cancel();
            }
        });
        dialog.show();
    }
    private void postData() {//充值

//        充值
//        @param str   token
//        @param Int   bankId   银行卡id  (type为1时必传)
//        @param Int   amount   金额        （加密）
//        @param Int   type     1-银行卡  2-支付宝  3-微信
//        @param Int   way      充值币种 1-余额  2-换购券  3-兑换币 4-现金券
        Map<String,Object> map = new HashMap<>();
        map.put("token", MyApplication.getInstance().getInfoBean().getToken());
        map.put("bankId", id);
        map.put("amount", Base64Util.encodedString2(amount));
        map.put("way", way);
        map.put("type", "1");
        XUtil.Post(Url.Ucenter_RECHARGE, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String re = jsonObject.getString("re");
                    if ("1".equals(re)) {
                        MyToast("提现成功");
                    }else if ("-1".equals(jsonObject.optString("re"))){
                        MyToast(getResources().getString(R.string.login_out));
                        MyApplication.getInstance().gotoLoginActivity();
                    }else {
                        MyToast(jsonObject.optString("info"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void onFinished() {
                super.onFinished();
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
            }
        });
    }
}
